package cn.andy.android.crm.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import cn.andy.android.crm.R;
import cn.andy.android.crm.beans.PersonInfo;
import cn.andy.android.crm.common.Util;
import cn.andy.android.crm.db.PersonDBHelper;

public class PersonEditUI extends AlertDialog.Builder{
	
	private View editview;
	private Context context;
	private PersonInfo person;
	private PersonDBHelper helper;

	public PersonEditUI(Context context, View editview, PersonInfo person, PersonDBHelper helper) {
		super(context);
		this.context = context;
		this.editview = editview;
		this.person = person;
		this.helper = helper;
		
		if(person != null) {
			EditText etname = (EditText) editview.findViewById(R.id.sqlitedemo_name);
			EditText etemail = (EditText) editview.findViewById(R.id.sqlitedemo_email);
			EditText etaddress = (EditText) editview.findViewById(R.id.sqlitedemo_address);
		
			etname.setText(person.getName());
			etemail.setText(person.getEmail());
			etaddress.setText(person.getAddress());
		}
		
		this.setTitle(R.string.person_editui_title).setView(editview).
		setNegativeButton(R.string.button_cancel,
				new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog,
					int which) {
				dialog.cancel();
			}
		}).
		setPositiveButton(R.string.button_save, savePerson).create().show();
	}
	
	public void afterDataUpdate(){
		
	}
	
	DialogInterface.OnClickListener savePerson = new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {

			EditText etname = (EditText) editview.findViewById(R.id.sqlitedemo_name);
			EditText etemail = (EditText) editview.findViewById(R.id.sqlitedemo_email);
			EditText etaddress = (EditText) editview.findViewById(R.id.sqlitedemo_address);

			String name = etname.getText().toString();
			String email = etemail.getText().toString();
			String address = etaddress.getText().toString();
			if(Util.isNullStr(name)){
				Toast.makeText(context, "Please Input Name", Toast.LENGTH_SHORT).show();
			}
			else if(Util.isNullStr(email)){
				Toast.makeText(context, "Please Input Email", Toast.LENGTH_SHORT).show();
			}
			else if(Util.isNullStr(address)){
				Toast.makeText(context, "Please Input Address", Toast.LENGTH_SHORT).show();
			}
			else{
				if(person == null){
					PersonInfo p = new PersonInfo();
					p.setName(name);
					p.setEmail(email);
					p.setAddress(address);
					helper.insert(p);
				} else {
					person.setName(name);
					person.setEmail(email);
					person.setAddress(address);
					helper.update(person, person.getId());
					person = null;
				}
				dialog.dismiss();
				afterDataUpdate();
			}
		}
	};
}